import { AbstractButton, Layout, Paragraph, WithMargins } from "@/components";
import { useCallback, useEffect, useState } from "react";
import { Input, View } from "@tarojs/components";
import { getCurrentPages, useDidShow, useRouter } from "@tarojs/taro";
import { colors } from "@/data/shared/colors";
import { useUserInfo } from "@/store/userDataContext";
import { useApplicationInfo } from "@/store/applicationDataContext";
import { setAuth, useAuth } from "@/store/authContext";
import { debounce } from "@/utils";
import Taro from "@tarojs/taro";
import { PagesNavigation } from "@/data/pages/pagesTypes";
import style from "./index.module.scss";

const MAX_MESSAGE_LENGTH = 30;

const PREDEFINED_MESSAGES = [
  "与你共启珠宝艺术之门！",
  "邀你步入令人神往的珠宝艺术世界！",
  "愿你享受一段美妙的珠宝艺术之旅！",
];

export default function UserGiftCardShareForm() {
  const { params } = useRouter();
  const { userInfoState } = useUserInfo();
  const { applicationState, dispatch } = useApplicationInfo();
  // Needed for User ID param population
  const { authState, dispatchAuthAction } = useAuth();
  // Gift card ID
  const { id } = params;

  const [sender, setSender] = useState<string>(
    userInfoState.userData?.userInfo.nickName ?? ""
  );
  const [receiver, setReceiver] = useState<string>("You");
  const [message, setMessage] = useState<string>("");

  // No-op, but just to get uid into authState
  useEffect(() => {
    setAuth(dispatchAuthAction, () => {});
  }, []);

  useEffect(() => {
    // Navigates away in background -> no matter if cancelled or not
    // Using redirect, but still need to keep track of delta
    if (applicationState.shareData.shared) {
      const currentPages = getCurrentPages();
      const reroutePath: PagesNavigation =
        "pages/user-gift-certificates-detail/index";
      const rerouteIndex = currentPages
        .map((page) => page.route)
        .indexOf(reroutePath);
      if (rerouteIndex > -1) {
        Taro.navigateBack({
          delta: currentPages.length - rerouteIndex,
        });
      }
    }
  }, [applicationState.shareData]);

  const debouncedMessageUpdate = useCallback(
    debounce(
      (params: {
        sender: string;
        receiver: string;
        message: string;
        id: string | undefined;
        uid: number;
      }) => {
        const { sender, receiver, message, id, uid } = params;

        dispatch({
          type: "SET_SHARE_DATA",
          data: {
            text: `请查收${sender}送给你的L'ÉCOLE礼品卡`,
            //imagePath: applicationState.shareData.imagePath,
            imagePath: "/assets/images/sharing-gifting.jpg",
            url: `pages/user-gift-certificates-detail/index?id=${id!}&senderId=${uid}&sender=${encodeURIComponent(
              sender
            )}&receiver=${encodeURIComponent(
              receiver
            )}&message=${encodeURIComponent(message)}`,
          },
        });
      },
      300
    ),
    []
  );

  const reusableSetMessageOnUpdate = () => {
    if (userInfoState.userData?.userInfo.uid) {
      debouncedMessageUpdate({
        sender,
        receiver,
        message,
        id,
        uid: userInfoState.userData.userInfo.uid,
      });
    }
  };

  // Added due to reload upon share -> need to set data again
  useDidShow(() => {
    reusableSetMessageOnUpdate();
  });

  // On any updates that change the sharable data, update context
  useEffect(() => {
    reusableSetMessageOnUpdate();
  }, [sender, receiver, message, userInfoState.userData]);

  return (
    <>
      <Layout>
        <View className={style["gift-certificate-details-wrapper"]}>
          <WithMargins>
            <View className={style.section}>
              <Paragraph className={style.label} noSpacing>
                赠礼者姓名
              </Paragraph>
              <Input
                className={style.input}
                type="text"
                onInput={(e) => {
                  setSender(e.detail.value);
                }}
                value={sender}
                placeholder={""}
                placeholderStyle={`color: ${colors.colorDark}`}
              />
            </View>

            <View className={style.section}>
              <Paragraph className={style.label} noSpacing>
                收礼者姓名
              </Paragraph>
              <Input
                className={style.input}
                type="text"
                onInput={(e) => {
                  setReceiver(e.detail.value);
                }}
                value={receiver}
                placeholder={""}
                placeholderStyle={`color: ${colors.colorDark}`}
              />
            </View>

            <View className={style.section}>
              <Paragraph className={style.label} noSpacing>
                祝福语
              </Paragraph>
              <Input
                className={style.input}
                type="text"
                onInput={(e) => {
                  setMessage(e.detail.value);
                }}
                value={message}
                maxlength={MAX_MESSAGE_LENGTH}
                placeholder={""}
                placeholderStyle={`color: ${colors.colorDark}`}
              />
            </View>

            <View className={style["defined-message-container"]}>
              {PREDEFINED_MESSAGES.map((messageCandidate) => (
                <View
                  key={messageCandidate}
                  onClick={() => {
                    setMessage(messageCandidate);
                  }}
                  className={`${style["message-button"]} ${
                    message === messageCandidate
                      ? style["message-button--active"]
                      : ""
                  }`}
                >
                  {messageCandidate}
                </View>
              ))}
            </View>
          </WithMargins>
        </View>
        <View className={style.dock}>
          <AbstractButton color="white-opacity" openType="share">
            赠送礼品卡
          </AbstractButton>
        </View>
      </Layout>
    </>
  );
}
